package cn.edu.xmu.oomall.customer.service;


import cn.edu.xmu.javaee.core.model.dto.UserDto;
import cn.edu.xmu.oomall.customer.dao.AddressDao;
import cn.edu.xmu.oomall.customer.dao.bo.Address;
import cn.edu.xmu.oomall.customer.dao.openfegin.RegionDao;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional(propagation = Propagation.REQUIRED)
@RequiredArgsConstructor
public class AddressService {
    private final static Logger logger = LoggerFactory.getLogger(AddressService.class);

    private final AddressDao addressDao;

    private final RegionDao regionDao;

    public void setDefaultAddress(Long addressId, UserDto user) {
        Address address = addressDao.findById(addressId);
        if(Objects.equals(address.getBeDefault(), Address.IS_DEFAULT)){
            logger.info("Address with id {} is already the default address", addressId);
           return;
        }
        address.setDefaultAddress(user);
    }


    public List<Address> retrieveAddress(UserDto user, Integer page, Integer pageSize) {

        return addressDao.retrieveAddress(user, page, pageSize).stream().map(bo -> {
            bo.setRegion(regionDao.findById(bo.getRegionId()));
            return bo;
        }).collect(Collectors.toList());
    }


    public void setAddress(UserDto user, Address address) {
        addressDao.save(address, user);
    }

    public void delAddress(Long addressId, UserDto user) {
        addressDao.delAddress(addressId,user);
    }
}
